package com.ctg.behavior.calc.controller.funnels;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.ctg.behavior.common.funnel.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.example.ExampleFunnelReportResult;
import com.ctg.behavior.calc.utils.CtDateUtils;
import com.ctg.behavior.calc.utils.CtFileUtils;
import com.ctg.behavior.common.CtgIdData;
import com.ctg.behavior.common.CtgIdRequest;
import com.ctg.behavior.common.CtgIdResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api")
public class FunnelController {

	@Value("${simulator.path}")
	private String simlutorPath;

	@PostMapping("/funnel/add/v2")
	public CtgIdResult funnelCreate(@RequestBody CtFunnelCreateRequest request) throws Exception {

		CtgIdResult result = new CtgIdResult();
		log.info("request={}", request);

		Long theCreateFileNumber = null;
		String filePath = simlutorPath + "/funnels/funnel";
		FileUtils.forceMkdir(new File(filePath));
		List<Long> fileNumbers = CtFileUtils.listFileNumbers(filePath);
		if (!fileNumbers.isEmpty()) {
			theCreateFileNumber = fileNumbers.get(fileNumbers.size() - 1);
			theCreateFileNumber += 1;
		} else {
			theCreateFileNumber = 100001L;
		}

		CtFunnelDetailData detailBody = JSON.parseObject(JSON.toJSONString(request.getReq()), CtFunnelDetailData.class);
		detailBody.setId(theCreateFileNumber);

		CtFunnelDetailResult ctFunnelDetailResult = new CtFunnelDetailResult();
		ctFunnelDetailResult.setValue(detailBody);
		ctFunnelDetailResult.setErrorCode("");
		ctFunnelDetailResult.setSuccess(true);
		ctFunnelDetailResult.setErrorMessage("");

		String targetFile = filePath + "/" + theCreateFileNumber + ".json";
		FileUtils.writeStringToFile(new File(targetFile), JSON.toJSONString(ctFunnelDetailResult), "UTF-8");

		//result.setMsg("created successfully!");
		CtgIdData idData = new CtgIdData();
		idData.setId(theCreateFileNumber);
		result.setValue(idData);

		return result;
	}

	@PostMapping("/funnel/update/v2")
	public CtgIdResult funnelUpdate(@RequestBody CtFunnelUpdateRequest request) throws Exception {

		CtgIdResult result = new CtgIdResult();
		log.info("request={}", request);

		Long theCreateFileNumber = request.getReq().getId();
		String filePath = simlutorPath + "/funnels/funnel";
		FileUtils.forceMkdir(new File(filePath));

		CtFunnelDetailData detailBody = JSON.parseObject(JSON.toJSONString(request.getReq()), CtFunnelDetailData.class);
		detailBody.setId(theCreateFileNumber);

		CtFunnelDetailResult ctFunnelDetailResult = new CtFunnelDetailResult();
		ctFunnelDetailResult.setValue(detailBody);
		ctFunnelDetailResult.setErrorCode("");
		ctFunnelDetailResult.setSuccess(true);
		ctFunnelDetailResult.setErrorMessage("");

		String targetFile = filePath + "/" + theCreateFileNumber + ".json";
		FileUtils.writeStringToFile(new File(targetFile), JSON.toJSONString(ctFunnelDetailResult), "UTF-8");

		//result.setMsg("updated successfully!");
		CtgIdData idData = new CtgIdData();
		idData.setId(theCreateFileNumber);
		result.setValue(idData);

		return result;
	}

	@PostMapping("/funnel/query/v2")
	public CtFunnelDetailResult funnelDetail(@RequestBody CtgIdRequest request) throws Exception {

		log.info("id={}", request.getReq().getId());

		Long theCreateFileNumber = request.getReq().getId();
		String filePath = simlutorPath + "/funnels/funnel";
		FileUtils.forceMkdir(new File(filePath));

		String bodyFile = filePath + "/" + theCreateFileNumber + ".json";
		String body = FileUtils.readFileToString(new File(bodyFile), "UTF-8");
		CtFunnelDetailResult detailData = JSON.parseObject(body, CtFunnelDetailResult.class);
		detailData.getValue().setId(theCreateFileNumber);
		return detailData;
	}

	@PostMapping("/funnel/list/v2")
	public CtFunnelListResult funnelList(@RequestBody CtFunnelListRequest request) throws Exception {

		CtFunnelListResult result = new CtFunnelListResult();
		log.info("limit={}", request.getReq().getLimit());

		String filePath = simlutorPath + "/funnels/funnel";
		FileUtils.forceMkdir(new File(filePath));

		List<CtFunnelData> funnelDataList = new ArrayList<>();
		result.getValue().setList(funnelDataList);

		List<Long> fileNumbers = CtFileUtils.listFileNumbers(filePath);
		for (Long oneItem : fileNumbers) {
			Long theCreateFileNumber = oneItem;
			String bodyFile = filePath + "/" + theCreateFileNumber + ".json";
			String body = FileUtils.readFileToString(new File(bodyFile), "UTF-8");
			CtFunnelDetailResult ctFunnelDetailResult = JSON.parseObject(body, CtFunnelDetailResult.class);
			CtFunnelData funnelData = JSON.parseObject(JSON.toJSONString(ctFunnelDetailResult.getValue()), CtFunnelData.class);
			funnelDataList.add(funnelData);
			funnelData.setCreateTime(CtDateUtils.getCurrentDate());
			funnelData.setUpdateTime(CtDateUtils.getCurrentDate());
		}

		//result.setMsg("list successfully!");

		return result;
	}

	@PostMapping("/funnels/report")
	public CtFunnelCalcResult report(@RequestBody CtFunnelCalcRequest request) throws Exception {
		CtFunnelCalcResult result = new CtFunnelCalcResult();

		log.info("id={}", request.getReq().getFunnelId());
		log.info("request", JSON.toJSONString(request));

		Long theCreateFileNumber = request.getReq().getFunnelId();
		String filePath = simlutorPath + "/funnels/report";
		FileUtils.forceMkdir(new File(filePath));

		File bodyFile = new File(filePath + "/" + theCreateFileNumber + ".json");
		String bodyString = null;
		if (bodyFile.exists()) {
			bodyString = FileUtils.readFileToString(bodyFile, "UTF-8");
		} else {
			bodyString = ExampleFunnelReportResult.example01;
		}

		result = JSON.parseObject(bodyString, CtFunnelCalcResult.class);

		return result;
	}

	@PostMapping("/funnels/reportTMU")
	public CtgIdResult report(@RequestBody FunnelCalcTMUInfo tmuInfo) throws Exception {
		CtgIdResult result = new CtgIdResult();

		log.info("id={}", tmuInfo.getRequest().getReq().getFunnelId());

		Long theCreateFileNumber = tmuInfo.getRequest().getReq().getFunnelId();
		String filePath = simlutorPath + "/funnels/report";
		FileUtils.forceMkdir(new File(filePath));

		String targetFile = filePath + "/" + theCreateFileNumber + ".json";
		FileUtils.writeStringToFile(new File(targetFile), JSON.toJSONString(tmuInfo.getResponse()), "UTF-8");

		//result.setMsg("report response body updload successfully!(test mode)");
		CtgIdData idData = new CtgIdData();
		idData.setId(theCreateFileNumber);
		result.setValue(idData);

		return result;
	}

}
